<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue'
import { getGoodsList } from '@/service/api/product'
import { useTable, useTableOperate } from '@/hooks/common/table'
import { removeEmptyValues } from '@/utils/common'
import { formatOptions, getColumns } from './config'
import Search from './search.vue'
import EditDrawer from '../_edit/index.vue'
import Specification from '../_specification/index.vue'

defineOptions({
  name: 'ShopTable',
})

const params = reactive<Api.Product.GoodsListParams>({
  tab: 'all',
  title: '',
  category_id: '',
  page: 1,
  limit: 10,
})

const config = ref({})

const { data, loading, columns, pagination, searchParams, getData, resetSearchParams } = useTable({
  apiFn: getGoodsList,
  apiParams: removeEmptyValues(params),
  columns: () => getColumns(config),
})

const { drawerVisible, editingData, operateType, handleEdit, closeDrawer, handleAdd, onDeleted } = useTableOperate(
  data as any,
  getData,
)

const specificationVisible = ref(false)
const goodsId = ref<number>(0)

const handleSpecification = (id, visible) => {
  specificationVisible.value = visible
  if (visible) {
    goodsId.value = id
  }
}

watchEffect(() => {
  config.value = {
    handleEdit,
    onDeleted,
    handleSpecification,
  }
})

const handleSubmit = () => {
  closeDrawer()
  getData()
}
</script>

<template>
  <NCard>
    <Search v-model:model="searchParams" :list="formatOptions(data)" @search="getData" @reset="resetSearchParams" />
    <div class="mb-5 flex items-center justify-between">
      <span class="flex gap-2">
        <NButton strong secondary type="info" size="small" class="bg-indigo-500 color-white" @click="handleAdd">新增
        </NButton>
        <NButton strong secondary type="error" size="small" class="bg-red-500 color-white">批量删除</NButton>
        <NButton size="small" class="border-gray-200 bg-white color-black">上架</NButton>
        <NButton size="small" class="border-gray-200 bg-white color-black">下架</NButton>
      </span>
      <span class="rounded-md p-2 pb-1 pt-1 hover:bg-gray-100">
        <icon-local-refresh class="text-18px text-red fw-800" />
      </span>
    </div>
    <NDataTable :loading :columns :data="data.list" remote :pagination :row-key="(row) => row.id" />
    <EditDrawer v-model:visible="drawerVisible" :row-data="editingData as any" :operate-type="operateType"
      :category-options="formatOptions(data)" @submitted="handleSubmit" />
    <Specification v-model:visible="specificationVisible" :goods-id="goodsId" />
  </NCard>
</template>
